import { defineStore } from 'pinia'
import { ref, onMounted } from 'vue'

export const useUserStore = defineStore('user', () => {
  // 响应式状态
  const name = ref('')
  const token = ref('')

  // 初始化时从localStorage加载
  onMounted(() => {
    const stored = localStorage.getItem('userInfo')?.split(' ');
    if (stored) {
      const { name: storedName, token: storedToken } = JSON.parse(stored)
      name.value = storedName
      token.value = storedToken
    }
  })

  // 保存用户信息
  const setUserInfo = (userName: string, userToken: string) => {
    name.value = userName
    token.value = userToken
    localStorage.setItem('userInfo', JSON.stringify({
      name: userName,
      token: userToken
    }))
  }

  // 清除用户信息
  const clearUserInfo = () => {
    name.value = ''
    token.value = ''
    localStorage.removeItem('userInfo')
  }

  return {
    name,
    token,
    setUserInfo,
    clearUserInfo
  }
})